package com.kitty.game.activity.service.other;

import com.kitty.common.utils.SpringUtils;
import com.kitty.common.core.SchedulerManager;
import com.kitty.game.activity.ActivityDataPool;
import com.kitty.game.activity.model.product.ActivityType;
import com.kitty.game.activity.model.product.YingXiongSet;
import com.kitty.game.activity.service.time.FightActivityHandler;
import com.kitty.game.config.NPC;
import com.kitty.game.enter.TitleInfo;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.map.model.GroupMapParam;
import com.kitty.game.mirror.model.FightMirror;
import com.kitty.game.mirror.model.MirrorFightParam;
import com.kitty.game.mirror.model.RoleMirror;
import com.kitty.game.mirror.service.FightMirrorService;
import com.kitty.game.npc.message.RespNpcContent;
import com.kitty.game.npc.model.NpcButton;
import com.kitty.game.pet.model.Pet;
import com.kitty.game.rank.service.handler.YingXiongRankHandler;
import com.kitty.game.role.model.Role;
import com.kitty.game.utils.Const;
import com.kitty.game.utils.TimeUtil;
import com.kitty.game.zhangmen.RespMasterInfo;
import com.kitty.listener.event.FightEndEvent;
import com.kitty.mina.message.MessagePusher;
import org.nutz.json.Json;
import org.nutz.lang.util.NutMap;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**英雄会处理类*/
@Component
public class YingXiongHuiHandler extends FightActivityHandler {
    private static final String LEVEL_NOT_ENOUGH = "你年岁尚轻，勤学苦练之后再来找我吧！[离开]";
    private static final String LEVEL_MORE = "你的修为已经超过我了，去找修为更高的人切磋吧。[离开]";
    private static final String IN_TEAM = "以多欺少，即便得胜亦是不武，还是一个人再来挑战我吧。[离开]";
    private static final String REMAIN_COUNT_NOT_ENOUGH = "你今天已经挑战过了，还是明天再来吧。[离开]";
    private static final String FIGHT_SELF = "只有不断的超越自己，才能成为真正的强者！[我要超越自己/"+ NpcButton.BEYONG_YINGXIONG.getKey()+"][知足常乐，我已满足了/离开]";
    private static final String IN_FIGHT = "这会儿正忙着呢，有什么事稍后再说。[离开]";
    private static final String NO_FIGHT_PET = "你还没有准备好参战宠物，这样打败你会说我胜之不武。[离开]";
    private static final String FIGHT_WIN = "恭喜你挑战{0}成功，3分钟内无其他玩家挑战你成功，你将获得{1}称谓！";
    private static final String FIGHT_WIN_SELF = "恭喜你成功超越自我！";
    private static final String FIGHT_WIN_FIRST_NUMOR = "[#Y夏总兵#n]恭喜#Y{0}#n在英雄会上挑战#Y英雄会评判员#n成功，获得#R{1}#n的称谓！大家向#Y{0}#n祝贺吧！";
    private static final String FIGHT_WIN_NUMOR = "[#Y夏总兵#n]恭喜#Y{0}#n在英雄会上挑战#Y{2}#n成功，并从#Y{2}#n手中继承了#R{1}#n的称谓！大家向#Y{0}#n祝贺吧！";
    private static final String FIHGT_FAIL = "你还是先回去勤加练习再来吧！[离开]";
    private static final String YINGXIONG_MESSGAE = "大家好，我是新晋英雄。";


    /**从传入map中获得对应数据*/
    public void loadCommonSet(Map<String ,String> commonSetMap) {
        String value = commonSetMap.get("ying_xiong_set");
        List<YingXiongSet> yingXiongSets = Json.fromJsonAsList(YingXiongSet.class, value);

        Map<Integer, YingXiongSet> yingXiongSetMap = new HashMap<>();
        for (YingXiongSet yingXiongSet : yingXiongSets) {
            yingXiongSetMap.put(yingXiongSet.getNpcId(), yingXiongSet);
        }
        ActivityDataPool.yingXiongSetMap = yingXiongSetMap;

        for (YingXiongSet yingXiongSet : yingXiongSets) {
            NPC npc = SpringUtils.getMapService().getNpc(yingXiongSet.getNpcId());
            npc.setTitle(yingXiongSet.getTitle());
        }
    }

    public YingXiongSet getYingXiongSet(int npcId) {
        return ActivityDataPool.yingXiongSetMap.get(npcId);
    }

    @Override
    protected String getNpcContent(Role role, NPC npc) {
        FightMirror fightMirror = SpringUtils.getMirrorService().getFightMirror(npc.getId());
        if (fightMirror != null) {
            YingXiongSet yingXiongSet = getYingXiongSet(npc.getId());
            if (yingXiongSet != null) {
                return yingXiongSet.getContent();
            }
        }

        return npc.getContent();
    }

    @Override
    public void sendNpcContent(Role role, NPC bossNpc, String content) {
        RespNpcContent respNpcContent = SpringUtils.getNpcService().getRespNpcContent(role, bossNpc, content);
        SpringUtils.getNpcService().sendRespNpcContent(role, respNpcContent);
    }

    @Override
    protected String getNpcContentNotFight(Role role, NPC bossNpc) {
        YingXiongSet yingXiongSet = getYingXiongSet(bossNpc.getId());
        if (yingXiongSet == null) {
            /**正常不应该执行到这里*/
            new RuntimeException(MessageFormat.format("没有英雄数据， npcId: {}, npcName: {}", bossNpc.getId(), bossNpc.getName()));
            return IN_FIGHT;
        }

        /**检测是否在战斗中*/
        if (bossNpc.isInFight()) {
            return IN_FIGHT;
        }
        /**小于可挑战等级*/
        if (role.getLevel() < yingXiongSet.getMinLevel()) {
            return LEVEL_NOT_ENOUGH;
        }
        /**大于可挑战等级*/
        if (role.getLevel() > yingXiongSet.getMaxLevel()) {
            return LEVEL_MORE;
        }

        /**不可组队*/
        if (teamService.isInTeam(role)) {
            return IN_TEAM;
        }

        /**没有挑战次数时*/
        if (SpringUtils.getActivityService().getRemainCount(role, ActivityType.YING_XIONG_HUI) <= 0) {
            return REMAIN_COUNT_NOT_ENOUGH;
        }
        /**没有参战宠物*/
        if (SpringUtils.getPetService().getPetById(role.getPetBox().getFightPetId(), role) == null) {
            return NO_FIGHT_PET;
        }

        FightMirror fightMirror = SpringUtils.getMirrorService().getFightMirror(bossNpc.getId());
        if (fightMirror != null) {
            /**挑战对象是自己时*/
            if (fightMirror.getRoleMirror().getUid() == role.getUid() && role.getTalk().popChooseParam("fight_yingxiong_beyond_confirm") == null) {
                return FIGHT_SELF;
            }
        }

        return null;
    }

    @Override
    protected void doStartFight(Role role, NPC bossNpc) {
        FightMirror fightMirror = SpringUtils.getMirrorService().getFightMirror(bossNpc.getId());
        if (fightMirror == null) {
            /**没有人挑战成功过，则根据挑战玩家数据生成镜像*/
            fightMirror = SpringUtils.getMirrorService().createFightMirror(bossNpc.getId(), role);
        }
        /**开始挑战时就增加完成次数*/
        SpringUtils.getActivityService().addFinishCount(role, ActivityType.YING_XIONG_HUI, 1);
        bossNpc.setCreateTime(System.currentTimeMillis());

        MirrorFightParam mirrorFightParam = new MirrorFightParam((byte) getFightType(role), bossNpc.getId(), fightMirror);
        SpringUtils.getMirrorService().startFight(role, mirrorFightParam);
    }

    @Override
    protected int getFightType(Role role) {
        return Const.fightType_yingxionghui;
    }

    @Override
    protected NPC getBossNpc(int npcId) {
        return SpringUtils.getMapService().getNpc(npcId);
    }

    @Override
    protected void clearNpcAfterWin(Role role, NPC bossNpc) {

    }

    @Override
    public void doFightWinForSingle(Role role, FightEndEvent fightEndEvent, NPC bossNpc) {
        super.doFightWinForSingle(role, fightEndEvent, bossNpc);

        /**替换英雄数据*/
        FightMirror fightMirror = SpringUtils.getMirrorService().createFightMirror(bossNpc.getId(), role);
        FightMirror oldFightMirror = SpringUtils.getMirrorService().getFightMirror(bossNpc.getId());
        SpringUtils.getMirrorService().addFightMirror(fightMirror);
        YingXiongSet yingXiongSet = getYingXiongSet(bossNpc.getId());
        fightMirror.getRoleMirror().setTitle(yingXiongSet.getTitle());
        fightMirror.getRoleMirror().setMessage(YINGXIONG_MESSGAE);

        /**更新npc外观*/
        bossService.broadcastNpcUpdate(new GroupMapParam(role), bossNpc);

        /**挑战自己的时候不需要再发称号*/
        if (oldFightMirror == null || oldFightMirror.getRoleMirror().getUid() != role.getUid()) {
            String name = oldFightMirror != null ? oldFightMirror.getRoleMirror().getName() : "";
            MessagePusher.pushMessage(role, new RespNotifyMiscEx(MessageFormat.format(FIGHT_WIN, name, yingXiongSet.getTitle())));

            Role oldRole = (oldFightMirror !=null ? SpringUtils.getPlayerService().getPlayerBy(oldFightMirror.getRoleMirror().getUid()) : null);
            /**旧的英雄称号马上收回*/
            delOldTitle(oldRole, yingXiongSet.getTitle());
            sendNumor(role, yingXiongSet.getTitle(), oldRole);
            /**新的英雄称号3分钟后发*/
            addTitle(role, bossNpc, yingXiongSet.getTitle(), oldRole);

            /**更新排行榜*/
            if (oldFightMirror != null) {
                updateRank(oldFightMirror);
            }
        } else {
            MessagePusher.pushMessage(role, new RespNotifyMiscEx(FIGHT_WIN_SELF));
        }
    }

    private void updateRank(FightMirror fightMirror) {
        if (fightMirror == null) {return ;}
        int time = getTime(fightMirror);
        RoleMirror roleMirror = fightMirror.getRoleMirror();
        SpringUtils.getBean(YingXiongRankHandler.class).update(String.valueOf(roleMirror.getUid()), roleMirror.getLevel(), roleMirror.getPartyName(), roleMirror.getName(), time);
    }

    private int getTime(FightMirror fightMirror) {
        if (fightMirror == null) {return 0;}
        return (int) ((System.currentTimeMillis() - fightMirror.getCreateTime()) / TimeUtil.ONE_SECOND);
    }

    /**发谣言*/
    private void sendNumor(Role role, String title, Role oldRole) {
        String msg = null;
        if (oldRole == null) {
            msg = MessageFormat.format(FIGHT_WIN_FIRST_NUMOR, role.getName(), title);
        } else {
            msg = MessageFormat.format(FIGHT_WIN_NUMOR, role.getName(), title, oldRole.getName());
        }
        /**发谣言*/
        SpringUtils.getChatService().sendNumor(msg, Const.BRODCAST_MSG_TYPE_ROLE);
    }

    /**收回旧称号*/
    private void delOldTitle(Role role, String title) {
        if (role == null) {return ;}
        SpringUtils.getRoleService().delTitle(role, title);
    }

    /**添加称号*/
    private void addTitle(Role role, NPC bossNpc, String title, Role oldRole) {
        /**3分钟后发称号*/
        SchedulerManager.getInstance().schedule(() -> {
            FightMirror newFightMirror = SpringUtils.getMirrorService().getFightMirror(bossNpc.getId());
            if (newFightMirror != null && newFightMirror.getRoleMirror().getUid() == role.getUid()) {
                /**发称号*/
                SpringUtils.getRoleService().addTitle(role, new TitleInfo(title, title));
            }
        }, 3* TimeUtil.ONE_MINUTE);
    }

    @Override
    protected void giveReward(Role role, FightEndEvent fightEndEvent, NPC bossNpc) {
        /**暂时奖励，后面再调整。2倍刷道奖励*/
        giveReward(role, fightEndEvent, bossNpc, 2);
    }

    protected void giveReward(Role role, FightEndEvent fightEndEvent, NPC bossNpc,  int rewardRate) {
        /**暂时奖励，后面再调整。*/
        int daohang = 150 * rewardRate;
        SpringUtils.getRoleService().addTao(role, daohang);

        int currPetId = role.getTempCache("fight_current_pet_id", 0);
        Pet pet = SpringUtils.getPetService().getPetById(currPetId, role);
        if (pet != null) {
            /**暂时奖励，后面再调整。*/
            int petWuxue = 2 * rewardRate;
            NutMap doubleStatus = role.getPropsStatus();
            int point = doubleStatus.getInt("pet");
            if (doubleStatus.getInt("petStatus") == 1 && point >= 4) {
                doubleStatus.setv("pet", point - 4);
                role.save();
                petWuxue = petWuxue * 2;
            }
            SpringUtils.getRoleService().addPetMatiral(role, pet, petWuxue);
        }
    }

    @Override
    protected void clearNpcTimeOut(NPC npc) {

    }

    @Override
    public void doFightFail(Role role, FightEndEvent fightEndEvent) {
        super.doFightFail(role, fightEndEvent);
        NPC bossNpc = getBossNpc(fightEndEvent.getNpcId());
        sendNpcContent(role, bossNpc, FIHGT_FAIL);
        giveFailReward(role, fightEndEvent, bossNpc);
    }

    protected void giveFailReward(Role role, FightEndEvent fightEndEvent, NPC bossNpc) {
        giveReward(role, fightEndEvent, bossNpc, 1);
    }

    /**超越自己*/
    public void beyondSelf(Role role, NPC bossNpc) {
        role.getTalk().pushChooseParam("fight_yingxiong_beyond_confirm", true);
        startFight(role, bossNpc);
    }

    /**查看英雄信息*/
    public void viewYingXiong(Role role, NPC npc) {
        FightMirror fightMirror = SpringUtils.getMirrorService().getFightMirror(npc.getId());

        RespMasterInfo respMasterInfo = null;
        if (fightMirror == null) {
            /**没有英雄数据*/
            YingXiongSet yingXiongSet = getYingXiongSet(npc.getId());
            RoleMirror roleMirror = new RoleMirror();
            roleMirror.setIcon(npc.getIcon());
            roleMirror.setName(npc.getName());
            roleMirror.setTitle(yingXiongSet.getTitle());
            roleMirror.setLevel(yingXiongSet.getMinLevel());
            roleMirror.setMessage(YINGXIONG_MESSGAE);
            respMasterInfo = new RespMasterInfo(role, roleMirror);
        } else {
            /**有英雄数据*/
            respMasterInfo = new RespMasterInfo(role, fightMirror.getRoleMirror());
        }

        MessagePusher.pushMessage(role, respMasterInfo);
    }

    /**每隔一段时间检测更新，排行榜的守护时间。*/
    public void updateRank() {
        Set<Integer> npcIds = ActivityDataPool.yingXiongSetMap.keySet();

        FightMirrorService fightMirrorService = SpringUtils.getBean(FightMirrorService.class);
        for (int npcId : npcIds) {
            FightMirror fightMirror = fightMirrorService.getFightMirror(npcId);
            if (fightMirror == null) { continue;}

            updateRank(fightMirror);
        }
    }
}
